package com.automobile.realm;

import com.automobile.domain.User;
import com.automobile.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * shiro用户登录认证
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-05-14 16:31
 */
public class UserRealm extends AuthorizingRealm {


    @Autowired
    @Lazy //必须延时加载，原因是bean实例化的顺序上，shiro的bean必须要先实例化，否则@Cacheable注解无效
    private UserService userService;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        User user = (User) principals.getPrimaryPrincipal();
        try {
//            for (Role role : user.getRoles()) {
//                //添加角色
//                simpleAuthorizationInfo.addRole(role.getRoleName());
//                //添加权限
//                for (Permissions permissions : role.getPermissions()) {
//                    simpleAuthorizationInfo.addStringPermission(permissions.getPermissionsName());
//                }
//            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return info;
    }


    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        String username = upToken.getUsername();

        System.out.println(username);

        User user = null;
        try {
            user = userService.loginUser(username);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(user==null){
            throw new UnknownAccountException("用户不存在");
        }

        if(user.getStatus().equals("N")){
            throw new LockedAccountException("账号未激活或被锁定");
        }

        ByteSource salt = ByteSource.Util.bytes(user.getPhone());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),salt,getName());

        return info;
    }
}
